package com.billdowney.qq.robot.controller;

import cn.hutool.core.util.StrUtil;
import com.billdowney.qq.robot.bean.BotBean;
import com.billdowney.qq.robot.bean.ResultBean;
import com.billdowney.qq.robot.service.RobotService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.mamoe.mirai.Bot;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

/**
 * @author BillDowney
 * @date 2021/3/31 21:53
 */
@Api(tags = "机器人操作接口")
@RequestMapping(path = "robot", method = {RequestMethod.POST, RequestMethod.GET})
@RestController
@Slf4j
public class RobotController {

    @Resource
    private RobotService robotService;

    @RequestMapping(path = "start")
    @ApiOperation(value = "启动机器人")
    public ResultBean<Object> start(String qq, String password) {
        // 启动机器人
        Thread qqRunThread = new Thread(() -> {
            robotService.start(qq, password);
        });
        qqRunThread.setDaemon(true);
        qqRunThread.setName("QQ机器人服务运行线程:" + qq);
        qqRunThread.start();
        return ResultBean.success();
    }

    @RequestMapping(path = "stop")
    @ApiOperation(value = "停止机器人")
    public ResultBean<Object> stop(String qq) {
        try {
            if (StrUtil.isNotEmpty(qq)) {
                try {
                    Bot.getInstance(Long.parseLong(qq)).close();
                } catch (NoSuchElementException e) {
                    log.error(e.getMessage(), e);
                    return ResultBean.error(String.format("不存在机器人示例:%s", qq));
                }
            } else {
                // 关闭机器人运行
                Bot.getInstances().forEach(bot -> bot.close(null));
            }
            return ResultBean.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.error(e.getMessage());
        }
    }

    @RequestMapping(path = "status")
    @ApiOperation(value = "机器人状态")
    public ResultBean<Object> status(String qq) {
        List<BotBean> list = new ArrayList<>();
        if (StrUtil.isEmpty(qq)) {
            if (!Bot.getInstances().isEmpty()) {
                Bot.getInstances().forEach(item -> {
                    list.add(new BotBean(item));
                });
            }
        } else {
            try {
                list.add(new BotBean(Bot.getInstance(Long.parseLong(qq))));
            } catch (NoSuchElementException e) {
                log.error(e.getMessage(), e);
                return ResultBean.error(String.format("不存在机器人示例:%s", qq));
            }
        }
        return ResultBean.success(list);
    }
}
